﻿using System.Runtime.Serialization;
using System.Collections.Generic;
using System.Linq;

namespace Collab.Services.Remote.Entities
{
    [DataContract(Namespace = "http://collab.codeplex.com/2010/10/Schemas")]
    public class UserSelection
    {
        

        [DataMember(Order = 1, IsRequired = true)]
        public int CaretPosition { get; set; }
        [DataMember(Order = 1, IsRequired = true)]
        public int CaretLine { get; set; }
        [DataMember(Order = 1, IsRequired = true)]
        public List<SelectionSpan> SelectedSpans { get; set; }
        public bool IsEmpty { get { return this.SelectedSpans.Count == 0; } }

        public UserSelection()
        {
            SelectedSpans = new List<SelectionSpan>();
        }

        // override object.Equals
        public override bool Equals(object obj)
        {
            //       
            // See the full list of guidelines at
            //   http://go.microsoft.com/fwlink/?LinkID=85237  
            // and also the guidance for operator== at
            //   http://go.microsoft.com/fwlink/?LinkId=85238
            //

            if (obj == null || GetType() != obj.GetType())
            {
                return false;
            }

            var other = obj as UserSelection;
            var isEqual = (this.CaretPosition == other.CaretPosition && this.SelectedSpans.Count == other.SelectedSpans.Count);
            if (isEqual)
            {
                for (int i = 0; i < this.SelectedSpans.Count; i++)
                {
                    if (this.SelectedSpans[i] != other.SelectedSpans[i])
                    {
                        isEqual = false;
                        break;
                    }
                }
            }
            return isEqual;
        }

        // override object.GetHashCode
        public override int GetHashCode()
        {
            return (CaretPosition + (this.SelectedSpans.Count * 20001) + this.SelectedSpans.Sum(span => span.GetHashCode())).GetHashCode();
        }
    }
}
